package com.syyo.gulimall.auth.web;

import com.alibaba.fastjson.TypeReference;
import com.syyo.common.constant.AuthConstant;
import com.syyo.common.domain.ResultVo;
import com.syyo.common.utils.MyJSONUtils;
import com.syyo.common.utils.MyStringUtils;
import com.syyo.common.utils.ResultUtils;
import com.syyo.common.vo.MemberVo;
import com.syyo.gulimall.auth.feign.MemberFeign;
import com.syyo.gulimall.auth.feign.ThirdPartyFeign;
import com.syyo.gulimall.auth.vo.UserLoginVo;
import com.syyo.gulimall.auth.vo.UserRegistVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ author: wang
 * @ date: 2021/4/15 14:19
 * @ Description:
 */
@Controller
public class LoginController {

    @Autowired
    ThirdPartyFeign thirdPartyFeign;

    @Autowired
    MemberFeign memberFeign;

    @Autowired
    StringRedisTemplate redisTemplate;
//    @GetMapping({"/login.html"})
//    public String loginHtml() {
//        return "login";
//    }
//
//    @GetMapping({"/reg.html"})
//    public String regHtml() {
//        return "reg";
//    }

    @ResponseBody
    @GetMapping("sms/code")
    public ResultVo sendCode(@RequestParam("phone") String phone) {
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                // 60秒内不能再发
                return ResultUtils.error("验证码发送频繁");
            }
        }

        String code = UUID.randomUUID().toString().substring(0, 5);
        code = code + "_" + System.currentTimeMillis();

//        thirdPartyFeign.sendSmsCode(phone,code);
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
        return ResultUtils.ok(1);
    }

    /**
     * @param user
     * @param result
     * @param redirectAttributes 模拟重定向携带的数据,使用这个可以解决刷新导致的重复提交
     * @return
     */
    @PostMapping({"/regist"})
    public String regist(@Valid UserRegistVo user, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
//            Map<String, String> collect = result.getFieldErrors().stream().collect(Collectors.toMap(fieldError -> {
//                return fieldError.getField();
//            }, fieldError -> {
//                return fieldError.getDefaultMessage();
//            }));
            // 简写
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
//            model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors", errors);

            // 校验出错，转发到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        // 注册
        String code = user.getCode();
        String redisCode = redisTemplate.opsForValue().get(user.getPhone());

//        if (!StringUtils.isEmpty(redisCode)){
        if (!StringUtils.isEmpty(redisCode)) {

            if (code.equals(redisCode.split("_")[0])) {
                // redisCode = DASH_15762121561000  验证码_时间戳
                // 验证码通过

                // 删除验证码
                redisTemplate.delete(user.getPhone());

                ResultVo resultVo = memberFeign.regist(user);

                if (resultVo.getCode() == 20000) {
                    // 成功
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    // 失败
                    HashMap<String, String> errors = new HashMap<>();
                    errors.put("msg", resultVo.getMessage());
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }

            } else {
                HashMap<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            HashMap<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

//        return "redirect:/login.html";
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {

        // 远程登录
        ResultVo resultVo = memberFeign.login(vo);
        if (resultVo.getCode() == 20000) {
            Object data = resultVo.getData();
            MemberVo memberVo = MyJSONUtils.typeCast(new TypeReference<MemberVo>() {
            }, data);

            session.setAttribute(AuthConstant.LOGIN_USER, memberVo);

            // 成功
            return "redirect:http://gulimall.com";
        } else {
            // 失败
            HashMap<String, String> errors = new HashMap<>();
            errors.put("msg", resultVo.getMessage());
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthConstant.LOGIN_USER);
        if (attribute == null) {
            // 没登录
            return "login";
        } else {
            // 已登录
            return "redirect:http://gulimall.com";
        }
    }
}
